package com.qmgyl.marketshop.purchase.controller;

import java.io.IOException;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.qmfresh.service.entity.ProcurementOrderItem;
import com.qmgyl.marketshop.api.ServiceApi;
import com.qmgyl.marketshop.vo.*;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import com.qmgyl.marketshop.common.*;
import org.springframework.web.servlet.ModelAndView;
import util.DateUtils;
import util.JsonUtil;


import util.Page;

@Controller
@RequestMapping(value = "/purchase")
public class PurchaseController {

    private static String PROCUREMENT_ITEM_LIST = "/shop/procurement/itemlist";
	private static String PROCUREMENT_LIST = "/shop/procurement/list";
	private static String PROCUREMENT_ITEM_UPDATE = "/shop/procurement/item/update";
	private static String PROCUREMENT_ITEM_CREATE = "/shop/procurement/create";
	private static String PROCUREMENT_DETAIL = "/shop/procurement/detail";
	private static String API_URL = "http://127.0.0.1:8080";

	@RequestMapping(value="/{name}", method = RequestMethod.GET)
	public String order(@PathVariable("name") String name){
		return "purchase/"+name;
	}
	



	/**
	 *  采购列表
	 * @param request
	 * @param response
	 * @throws IOException
	 */
	@RequestMapping(value="getList")
	@ResponseBody
	public void getList(Integer page,Integer rows,Integer applySource,Integer status,String sTime,String eTime, HttpServletRequest request, HttpServletResponse response) throws IOException{
		if(null == page){
			page = 1;
		}
		if(null == rows){
			rows = 10;
		}
		ProcurementQuery procurementQuery = new ProcurementQuery();
		//procurementQuery.setShopId(5);
		procurementQuery.setPageIndex(page);
		procurementQuery.setPageSize(rows);
		procurementQuery.setApplySource(applySource);
		procurementQuery.setStatus(status);

		procurementQuery.setStartTime(DateUtils.transForMilliSecondByTim(sTime,"yyyy-MM-dd"));
		procurementQuery.setEndTime(DateUtils.transForMilliSecondByTim(eTime,"yyyy-MM-dd"));

		String result = HttpUtils.postRequestBody(API_URL + PROCUREMENT_LIST,procurementQuery);

		ServiceResult<ListWithPage<ProcurementOrder>> sr = JSONObject.parseObject(result, new TypeReference<ServiceResult<ListWithPage<ProcurementOrder>>>(){});
		System.out.println("str:"+sr.getBody().getListData());

		Map<String, Object> data = new HashMap<String, Object>();
		data.put("total", sr.getBody().getTotalCount());

		List<ProcurementOrder> listData = setProcurementItemList((sr.getBody().getListData()));
		data.put("rows", listData);
		response.setContentType("application/json;charset=UTF-8");
		System.out.println(JSONObject.toJSONString(data));
		response.getWriter().write(JSONObject.toJSONString(data));

	}

	private List<ProcurementOrder> setProcurementItemList(List<ProcurementOrder> listData){
		List<ProcurementOrder> orderList =  new ArrayList<>(listData.size());
		for (ProcurementOrder od : listData) {
			ProcurementOrder odv = new ProcurementOrder();
			if (od.getApplySource() == 2) {
				odv.setApplySourceName("B端用户");
			} else {
				odv.setApplySourceName("C端用户");
			}
			switch (od.getStatus()) {
				case 0:
					odv.setStatusName("取消");
					break;
				case 1:
					odv.setStatusName("待入库");
					break;
				case 2:
					odv.setStatusName("部分入库");
					break;
				case 3:
					odv.setStatusName("全部入库");
					break;
				case 4:
					odv.setStatusName("待确认");
					break;
				case 5:
					odv.setStatusName("超时未入库");
					break;
				default:
					break;
			}
			odv.setDeliveryDateTime(DateUtils.transForDateString(od.getDeliveryTime()));
			odv.setApplyDateTime(DateUtils.transForDateString(od.getApplyTime()));
			odv.setApplySource(od.getApplySource());
			odv.setId(od.getId());
			odv.setStatus(od.getStatus());
			odv.setApplyTime(od.getApplyTime());
			odv.setDeliveryTime(od.getDeliveryTime());
			odv.setSkuNum(od.getSkuNum() == null ? 0 : od.getSkuNum());
			odv.setTotalPrice(od.getTotalPrice() == null ? BigDecimal.valueOf(0L) : od.getTotalPrice());
			orderList.add(odv);
		}
		return orderList;
	}

    @RequestMapping(value="/detail", method = RequestMethod.GET)
    public ModelAndView detail(String id, HttpServletRequest request, HttpServletResponse response){
		ModelAndView mav = new ModelAndView();

        List<ProcurementOrderItemResult> listData =  getItem(id);
        mav.addObject("listData",listData);
        mav.setViewName("purchase/detail");
        return mav;
    }

    private List<ProcurementOrderItemResult> getItem(String id){


		String result = HttpUtils.postRequestBody(API_URL + PROCUREMENT_ITEM_LIST,id);
		ServiceResult<List<ProcurementOrderItemResult>> sr = JSONObject.parseObject(result, new TypeReference<ServiceResult<List<ProcurementOrderItemResult>>>(){});

		return sr.getBody();
	}

	@RequestMapping(value="add")
	public ModelAndView add(String id, HttpServletRequest request, HttpServletResponse response){
		ModelAndView mav = new ModelAndView();
		if(StringUtils.isNotEmpty(id) && StringUtils.isNotEmpty("0")){
			// 修改
			String result = HttpUtils.postRequestBody(API_URL + PROCUREMENT_DETAIL,id);
			ServiceResult<ProcurementOrder> sr = JSONObject.parseObject(result, new TypeReference<ServiceResult<ProcurementOrder>>(){});
			List<ProcurementOrder> list = new ArrayList<>();
			list.add(sr.getBody());
			;
			mav.addObject("procurementOrder",setProcurementItemList(list).get(0));
			mav.addObject("edit","1");
			List<ProcurementOrderItemResult> listData =  getItem(id);
			mav.addObject("listData",listData);
		}else{
			mav.addObject("edit","0");
		}
		mav.setViewName("purchase/add");
		return mav;
	}

	@RequestMapping(value="/update/item")
	@ResponseBody
	public void updateItem(ProcurementOrderItem item, HttpServletRequest request, HttpServletResponse response) throws IOException{

		//item.setShopId(5);
		List<ProcurementOrderItem> list = new ArrayList<ProcurementOrderItem>();

	 	list.add(item);
		String result = HttpUtils.postRequestBody(API_URL + PROCUREMENT_ITEM_UPDATE,list);

		ServiceResult<Boolean> sr = JSONObject.parseObject(result, new TypeReference<ServiceResult<Boolean>>(){});
		System.out.println("str:"+sr.getBody());

		Map<String, Object> data = new HashMap<String, Object>();

		response.setContentType("application/json;charset=UTF-8");
		System.out.println(JSONObject.toJSONString(data));

		response.getWriter().write(JSONObject.toJSONString(data));

	}

	@RequestMapping(value="/create")
	@ResponseBody
	public void create(ProcurementOrderItem item, HttpServletRequest request, HttpServletResponse response) throws IOException{

		//item.setShopId(5);
		List<ProcurementOrderItem> list = new ArrayList<ProcurementOrderItem>();

		list.add(item);
		String result = HttpUtils.postRequestBody(API_URL + PROCUREMENT_ITEM_CREATE,list);

		ServiceResult<Long> sr = JSONObject.parseObject(result, new TypeReference<ServiceResult<Long>>(){});
		//System.out.println("str:"+sr.getBody());

		Map<String, Object> data = new HashMap<String, Object>();

		response.setContentType("application/json;charset=UTF-8");
		System.out.println(JSONObject.toJSONString(data));

		response.getWriter().write(sr.getBody().toString());

	}
	
}